#!/bin/bash

# this should take latest varsion of peac-installer and execute it

CURRENT_PEAC_INSTALLER_NAME="/tmp/${USER}-peac-installer.sh"


function CheckPEACInstallerVersion() {
  if [ ! -f $CURRENT_PEAC_INSTALLER_NAME ];then
    return 1
  fi

  existing_version=`cat $CURRENT_PEAC_INSTALLER_NAME`
  existing_version=`echo $existing_version | sed -r -e 's/.*PEAC_VERSION\s*=\s*([[:digit:]]+.[[:digit:]]+).*/\1/'`

  latest_version=`wget -q -O - http://peac.googlecode.com/svn/trunk/scripts/peac-installer.sh`
  latest_version=`echo $latest_version | sed -r -e 's/.*PEAC_VERSION\s*=\s*([[:digit:]]+.[[:digit:]]+).*/\1/'`

  ex_maj=${existing_version%.*}
  ex_min=${existing_version#*.}
  lat_maj=${latest_version%.*}
  lat_min=${latest_version#*.}

  if [ $ex_maj -lt $lat_maj ]; then
    rm -f $1
    return 2
  elif [ $ex_maj -eq $lat_maj ]; then
    if [ $ex_min -lt $lat_min ]; then
    rm -f $1
    return 3
    fi
  fi

  return 0
}

CheckPEACInstallerVersion $CURRENT_PEAC_INSTALLER_NAME
if [ "$?" != "0" ]; then
  echo "Upgrading peac-installer ..."
  wget -q -O $CURRENT_PEAC_INSTALLER_NAME http://peac.googlecode.com/svn/trunk/scripts/peac-installer.sh
  if [ "$?" != "0" ];then 
    echo "Problem downloading latest peac-installer !!!"
    exit 1
  fi
fi

chmod +x $CURRENT_PEAC_INSTALLER_NAME
. $CURRENT_PEAC_INSTALLER_NAME $*
